<template>
  <div class="chat-panel">
    <div class="chat-header" v-if="selectedCharacter">
      <div class="chat-info">
        <div class="chat-avatar">{{ characterEmoji }}</div>
        <div class="chat-details">
          <h3>与 {{ selectedCharacter.name }} 对话中</h3>
          <p>{{ characterRole }}</p>
        </div>
      </div>
      <div class="chat-actions">
        <el-button type="text" @click="emit('clearMessages')" class="action-btn">
          <el-icon><Delete /></el-icon>
          清空
        </el-button>
        <el-button type="text" class="action-btn">
          <el-icon><Microphone /></el-icon>
          开启语音对话
        </el-button>
      </div>
    </div>

    <!-- 消息区域 -->
    <div class="messages-container" ref="messagesContainer">
      <div v-if="messages.length === 0" class="welcome-message">
        <div class="welcome-content">
          <div class="welcome-icon">💬</div>
          <h3>开始你的对话之旅</h3>
          <p>向{{ selectedCharacter?.name || '角色' }}说点什么吧！</p>
        </div>
      </div>
      
      <div
        v-for="message in messages"
        :key="message.id"
        :class="['message', message.type]"
      >
        <div class="message-avatar">
          <div v-if="message.type === 'character'" class="character-msg-avatar">
            <img 
              v-if="characterAvatarUrl" 
              :src="characterAvatarUrl" 
              :alt="selectedCharacter?.name" 
              class="character-msg-avatar-image"
              @error="handleImageError"
            />
            <span v-else>{{ characterEmoji }}</span>
          </div>
          <el-avatar v-else :size="36">{{ username?.charAt(0)?.toUpperCase() }}</el-avatar>
        </div>
        <div class="message-content">
          <div class="message-header">
            <span class="message-name">{{ message.name }}</span>
            <span class="message-time">{{ formatTime(message.timestamp) }}</span>
          </div>
          <div class="message-text">
            <MessageRenderer :content="message.content" />
          </div>
          <div class="message-actions" v-if="message.type === 'character'">
            <el-button type="text" size="small" @click="emit('playAudio', message)">
              <el-icon><VideoPlay /></el-icon>
              播放语音
            </el-button>
          </div>
        </div>
      </div>
      
      <!-- AI思考指示器 -->
      <div v-if="isThinking" class="message character">
        <div class="message-avatar">
          <div class="character-msg-avatar">
            <img 
              v-if="characterAvatarUrl" 
              :src="characterAvatarUrl" 
              :alt="selectedCharacter?.name" 
              class="character-msg-avatar-image"
              @error="handleImageError"
            />
            <span v-else>{{ characterEmoji }}</span>
          </div>
        </div>
        <div class="message-content">
          <div class="thinking-indicator">
            <div class="thinking-dots">
              <span></span><span></span><span></span>
            </div>
            <span class="thinking-text">{{ selectedCharacter?.name }} 正在思考...</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-area">
      <div class="input-container">
        <el-input
          :modelValue="inputMessage"
          @update:modelValue="emit('updateInput', $event)"
          type="textarea"
          :rows="2"
          placeholder="输入你想说的话..."
          @keydown.enter="handleKeyDown"
          :disabled="!selectedCharacter"
          class="message-input"
        />
        <div class="input-actions">
          <div class="emoji-container">
            <el-button type="text" @click="toggleEmojiPicker" class="input-action-btn">
              <el-icon><Sunny /></el-icon>
            </el-button>
            <EmojiPicker 
              :show="showEmojiPicker" 
              @select="insertEmoji"
              @close="showEmojiPicker = false"
            />
          </div>
          <div class="file-container">
            <el-button type="text" @click="toggleFileUploader" class="input-action-btn">
              <el-icon><Paperclip /></el-icon>
            </el-button>
            <FileUploader 
              :show="showFileUploader" 
              @uploadComplete="handleFileUploadComplete"
              @close="showFileUploader = false"
            />
          </div>
          <el-button
            type="primary"
            @click="emit('sendMessage')"
            :disabled="!inputMessage.trim() || !selectedCharacter || isThinking"
            class="send-btn"
          >
            <el-icon><Position /></el-icon>
            发送
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick, onMounted, onUnmounted } from 'vue'
import {
  Delete, Download, VideoPlay, ChatLineRound,
  Sunny, Paperclip, Position, Microphone
} from '@element-plus/icons-vue'
import type { Character, LegacyCharacter, Message } from '../../types/novel'
import EmojiPicker from '../common/EmojiPicker.vue'
import FileUploader from '../common/FileUploader.vue'
import MessageRenderer from '../common/MessageRenderer.vue'

interface Props {
  selectedCharacter: Character | LegacyCharacter | null
  messages: Message[]
  isThinking: boolean
  inputMessage: string
  username?: string
}

const props = defineProps<Props>()

// 计算属性用于兼容新旧数据结构
const characterRole = computed(() => {
  if (!props.selectedCharacter) return ''
  
  // 如果是旧格式的角色数据
  if ('role' in props.selectedCharacter) {
    return (props.selectedCharacter as LegacyCharacter).role
  }
  
  // 新格式使用role_type映射
  const roleMap: Record<string, string> = {
    protagonist: '主角',
    supporting: '配角',
    antagonist: '反角',
    minor: '次要角色'
  }
  return roleMap[props.selectedCharacter.role_type] || '角色'
})

const characterLocation = computed(() => {
  if (!props.selectedCharacter) return ''
  
  // 如果是旧格式的角色数据
  if ('novel' in props.selectedCharacter) {
    return (props.selectedCharacter as LegacyCharacter).novel
  }
  
  // 新格式需要从父组件传入小说标题，这里先显示占位符
  return '未知世界'
})

const characterEmoji = computed(() => {
  if (!props.selectedCharacter) return '👤'
  
  // 如果是旧格式的角色数据
  if ('emoji' in props.selectedCharacter) {
    return (props.selectedCharacter as LegacyCharacter).emoji
  }
  
  // 新格式默认头像
  return '👤'
})

const characterAvatarUrl = computed(() => {
  if (!props.selectedCharacter) return null
  
  // 如果是新格式的角色数据并且有头像图片
  if ('avatar_image' in props.selectedCharacter && props.selectedCharacter.avatar_image) {
    return props.selectedCharacter.avatar_image
  }
  
  return null
})

const handleImageError = () => {
  console.warn('角色头像加载失败:', props.selectedCharacter?.name)
}

const emit = defineEmits<{
  clearMessages: []
  exportChat: []
  playAudio: [message: Message]
  likeMessage: [message: Message]
  updateInput: [value: string]
  insertEmoji: []
  uploadFile: []
  sendMessage: []
}>()

const messagesContainer = ref<HTMLElement>()
const showEmojiPicker = ref(false)
const showFileUploader = ref(false)

// 自动滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 监听消息变化，自动滚动到底部
watch(() => props.messages, () => {
  scrollToBottom()
}, { flush: 'post' })

// 表情选择器相关方法
const toggleEmojiPicker = () => {
  showEmojiPicker.value = !showEmojiPicker.value
}

const insertEmoji = (emoji: string) => {
  const currentInput = props.inputMessage
  const newInput = currentInput + emoji
  emit('updateInput', newInput)
  showEmojiPicker.value = false
}

// 文件上传相关方法
const toggleFileUploader = () => {
  showFileUploader.value = !showFileUploader.value
}

const handleFileUploadComplete = (files: any[]) => {
  // 将上传的文件信息以标签形式插入到输入框中
  let fileText = ''
  files.forEach(file => {
    // 截取文件名前5个字符，如果超过5个字符则添加省略号
    const displayName = file.name.length > 5 ? file.name.substring(0, 5) + '...' : file.name
    fileText += `[${displayName}] `
  })
  
  const currentInput = props.inputMessage
  const newInput = currentInput + fileText
  emit('updateInput', newInput)
  showFileUploader.value = false
}

// 处理键盘事件
const handleKeyDown = (event: KeyboardEvent) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault()
    emit('sendMessage')
  }
}

// 点击外部关闭选择器
const handleClickOutside = (event: Event) => {
  const target = event.target as HTMLElement
  if (!target.closest('.emoji-container') && !target.closest('.emoji-picker')) {
    showEmojiPicker.value = false
  }
  if (!target.closest('.file-container') && !target.closest('.file-uploader')) {
    showFileUploader.value = false
  }
}

onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})

// 监听思考状态变化，自动滚动到底部
watch(() => props.isThinking, () => {
  scrollToBottom()
}, { flush: 'post' })

const formatTime = (date: Date) => {
  return date.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  })
}
</script>

<script lang="ts">
export default {
  name: 'ChatPanel'
}
</script>

<style scoped>
.chat-panel {
  display: flex;
  flex-direction: column;
  background: white;
  height: 100vh;
}

.chat-header {
  padding: 20px 24px;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chat-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.chat-avatar {
  width: 40px;
  height: 40px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
}

.chat-details h3 {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 2px;
}

.chat-details p {
  font-size: 12px;
  color: #6b7280;
  margin: 0;
}

.chat-actions {
  display: flex;
  gap: 8px;
}



.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 20px 24px;
  min-height: 0;
  max-height: calc(100vh - 200px);
  scroll-behavior: smooth;
}

.welcome-message {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
}

.welcome-content {
  text-align: center;
  color: #6b7280;
}

.welcome-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.welcome-content h3 {
  margin: 0 0 8px 0;
  color: #374151;
}

.welcome-content p {
  margin: 0;
}

.message {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
  align-items: flex-start;
}

.message.user {
  flex-direction: row-reverse;
}

.message-content {
  max-width: 70%;
  min-width: 0;
}

.message.user .message-content {
  text-align: right;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
  gap: 12px;
}

.message.user .message-header {
  flex-direction: row-reverse;
}

.message-name {
  font-size: 12px;
  font-weight: 600;
  color: #374151;
}

.message-time {
  font-size: 11px;
  color: #9ca3af;
}

.message-text {
  background: #f8fafc;
  padding: 12px 16px;
  border-radius: 18px;
  word-wrap: break-word;
  line-height: 1.4;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.message.user .message-text {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
}

.message-actions {
  margin-top: 8px;
  display: flex;
  gap: 12px;
}

.character-msg-avatar {
  width: 36px;
  height: 36px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  overflow: hidden;
}

.character-msg-avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 50%;
}

.thinking-indicator {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  background: #f8fafc;
  border-radius: 18px;
}

.thinking-dots {
  display: flex;
  gap: 4px;
}

.thinking-dots span {
  width: 6px;
  height: 6px;
  background: #9ca3af;
  border-radius: 50%;
  animation: thinkingDots 1.4s ease-in-out infinite both;
}

.thinking-dots span:nth-child(1) { animation-delay: -0.32s; }
.thinking-dots span:nth-child(2) { animation-delay: -0.16s; }
.thinking-dots span:nth-child(3) { animation-delay: 0s; }

@keyframes thinkingDots {
  0%, 80%, 100% { transform: scale(0.8); opacity: 0.5; }
  40% { transform: scale(1.2); opacity: 1; }
}

.thinking-text {
  font-size: 12px;
  color: #6b7280;
}

.input-area {
  padding: 20px 24px;
  border-top: 1px solid #e5e7eb;
}

.input-container {
  display: flex;
  gap: 12px;
  align-items: flex-end;
}

.message-input {
  flex: 1;
}

.input-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.emoji-container {
  position: relative;
}

.file-container {
  position: relative;
}

.input-action-btn {
  color: #6b7280;
  font-size: 16px;
}

.send-btn {
  height: 48px;
  padding: 0 24px;
}
</style> 